package com.example.redisdemo.handle;

import com.alibaba.fastjson.JSONException;
import com.example.redisdemo.core.AjaxResult;
import io.netty.handler.codec.DecoderException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.annotation.Order;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import javax.net.ssl.SSLException;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;

/**
 * 全局异常处理,
 * 只会处理所有 Controller 层抛出的 Exception 及其子类的异常
 *
 * @author hexinglin
 * @created 2022-06-08 17:55
 **/

@RestControllerAdvice
public class GlobalExceptionHandler {
    private static final Logger log = LoggerFactory.getLogger(GlobalExceptionHandler.class);
    /**
     * 拦截未知的运行时异常
     */
    @ExceptionHandler(RuntimeException.class)
    public AjaxResult handleRuntimeException(RuntimeException e, HttpServletRequest request)
    {
        String requestURI = request.getRequestURI();
        log.error("请求地址'{}',发生未知异常.{}", requestURI, e.getMessage());
        return AjaxResult.error(e.getMessage());
    }
   /**缺少必要的参数*/
    @ExceptionHandler(DecoderException.class)
    public AjaxResult decoderExceptionHandler(DecoderException e, HttpServletRequest request) {
        log.error("{}, SSLException:{}",  e.getMessage(), e);
        return AjaxResult.error(e.getMessage());
    }

    /**缺少必要的参数*/
    @ExceptionHandler(SSLException.class)
    public AjaxResult sslExceptionHandler(SSLException e, HttpServletRequest request) {
        log.error("{}, SSLException:{}",  e.getMessage(), e);
        return AjaxResult.error(e.getMessage());
    }

    /**缺少必要的参数*/
    @ExceptionHandler(IOException.class)
    public AjaxResult ioExceptionHandler(IOException e, HttpServletRequest request) {
        log.error("{}, IOException:{}",  e.getMessage(), e);
        return AjaxResult.error(e.getMessage());
    }
   /**缺少必要的参数*/
    @ExceptionHandler(JSONException.class)
    public AjaxResult jsonExceptionHandler(JSONException e, HttpServletRequest request) {
        log.error("{}, JSONException:{}",  e.getMessage(), e);
        return AjaxResult.error(e.getMessage());
    }

}
